package com.example.zhu.service.Impl;

import com.example.zhu.dto.OrderCountDTO;
import com.example.zhu.entity.*;
import com.example.zhu.mapper.FakeMapper;
import com.example.zhu.mapper.OrderCountMapper;
import com.example.zhu.mapper.OrderMapper;
import com.example.zhu.result.Result;
import com.example.zhu.service.OrderCountService;
import com.example.zhu.utils.RegularExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderCountServiceImpl implements OrderCountService {

    @Autowired
    private OrderCountMapper orderCountMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private FakeMapper fakeMapper;

    /**
     * 更新取件码
     *
     * @param orderCountDTO
     * @return
     */
    @Transactional
    public synchronized Result update(OrderCountDTO orderCountDTO) {

        Integer id2 = orderCountDTO.getId();

        Orders orders = orderMapper.selectById(id2);

        Integer orderStatus = orders.getOrderStatus();
        if(orderStatus == 1){
            return Result.error("待接单状态，禁止分件!");
        }

        if (orderCountDTO.getTakeCodes() == null && orderCountDTO.getTakeCodes().size() != 0) {
            return Result.error("数据异常,取件码为null");
        }

        List<OrderCount> counts_ = orderCountDTO.getTakeCodes();
        for (OrderCount count : counts_) {
            String takeCode = count.getTakeCode();
            if (!RegularExpression.verify_(takeCode)) {
                return Result.error("格式错误");
            }
        }

        Set<String> judge = counts_.stream().map(OrderCount::getTakeCode).collect(Collectors.toSet());

        if (judge.size() != counts_.size()) {
            return Result.error("取件码填写重复！");
        }

        List<String> codes = counts_.stream().map(OrderCount::getTakeCode).collect(Collectors.toList());
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd");
        LocalDateTime now = LocalDateTime.now();
        LocalDate localDate = now.toLocalDate();
        String dateStr = localDate.format(fmt);

        String[] split = dateStr.split("-");
        String s = split[1];
        int num = Integer.parseInt(s);

        if (num < 10) {
            dateStr = split[0] + "-" + num;
        }

        List<OrderCountDetail> list = orderCountMapper.selectAllCounts(dateStr, orderCountDTO.getId());


//        List<OrderCountDetail> list = orderCountMapper.selectAllCounts("12-1", orderCountDTO.getId());

        for (OrderCountDetail orderCountDetail : list) {
            String takeCode = orderCountDetail.getTakeCode();
            if (codes.contains(takeCode)) {
                Long number = orderCountDetail.getNumber();
                Order order = orderMapper.selectByNumber(number);
                return Result.error(order.getPhone() + " " + orderCountDetail.getTakeCode());
            }
        }

        //获取订单id
        Integer id = orderCountDTO.getId();


        //更新count数量
        if (orderCountDTO.getCount() != null && orderCountDTO.getCount() != 0) {
            orderMapper.updateCount(id, orderCountDTO.getCount(), LocalDateTime.now());
        } else {
            return Result.error("数据异常,count为null");
        }

        //新数据
        List<OrderCount> counts = orderCountDTO.getTakeCodes();

        /**
         * 分件 单件直接分类
         * 多件 直接分为疑难件
         */
        //21:1-41房间里 22:66-74房间外 23:快递柜和88
        if (counts.size() == 1) {
            String takeCode = counts.get(0).getTakeCode();
            Integer takeStatus = counts.get(0).getTakeStatus();
            Long id1 = counts.get(0).getId();
            if (takeStatus == 2) {

                if (RegularExpression.yd8(takeCode) || RegularExpression.jd(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 21);
                } else if (RegularExpression.s3d41(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 22);
                } else if (RegularExpression.s2d38(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 23);
                } else if (RegularExpression.sf(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 21);
                } else if (RegularExpression.cabinet(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 24);
                } else if (RegularExpression.pdd(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 21);
                } else if (RegularExpression.kf(takeCode)) {
                    orderMapper.update(id, LocalDateTime.now(), 25);
                } else {
                    return Result.error("格式错误");
                }
            }

        } else {
            boolean flag = true;
            for (OrderCount count : counts) {

                Integer takeStatus = count.getTakeStatus();

                if (takeStatus == -3) {
                    flag = false;
                    break;
                }

            }
            if (flag) {
                orderMapper.update(id, LocalDateTime.now(), -2);
            } else {
                orderMapper.update(id, LocalDateTime.now(), -3);
            }
        }


        //旧数据
        List<OrderCount> orderCounts_ = orderCountMapper.selectByOrderId(id);

        //考虑没有添加过的情况
        if (orderCounts_ == null || orderCounts_.size() == 0) {
            for (OrderCount count : counts) {
                OrderCount orderCount = OrderCount.builder()
                        .orderId(id)
                        .takeCode(count.getTakeCode())
                        .takeStatus(2)
                        .serverRemark(count.getServerRemark())
                        .helperRemark(count.getHelperRemark())
                        .build();
                orderCountMapper.insert(orderCount);
            }
            return Result.success();
        }

        //考虑添加过的情况
        //1.增加和修改
        for (OrderCount count : counts) {

            //如果是新件，则添加
            if (count.getId() == null) {
                OrderCount orderCount = OrderCount.builder()
                        .orderId(id)
                        .takeCode(count.getTakeCode())
                        .takeStatus(2)
                        .serverRemark(count.getServerRemark())
                        .helperRemark(count.getHelperRemark())
                        .build();
                orderCountMapper.insert(orderCount);

                //如果不是新件,则修改，修改前对于取件码状态为已取件的，不做修改
            } else {
                for (OrderCount orderCount : orderCounts_) {
                    if (orderCount.getId().equals(count.getId())) {
                        if (orderCount.getTakeStatus() == 3) {
                            continue;
                        } else if (orderCount.getTakeStatus() == -3) {
                            fakeMapper.updateStateByCountId(Math.toIntExact(orderCount.getId()), -3);
                        }
                        orderCountMapper.updateOrderCount(count);
                    }
                }
            }

        }


        //获取旧数据的id集合，准备比对新数据
        List<Long> ids = new ArrayList<>();
        for (OrderCount count : counts) {
            ids.add(count.getId());
        }

        //2.删除
        //比对旧数据和新数据的id，新数据没有，但是旧数据有，需要删除旧数据
        for (OrderCount orderCount : orderCounts_) {
            Long id_ = orderCount.getId();
            if (!ids.contains(id_)) {
                orderCountMapper.deleteById(id_);
            }
        }

//        List<Long> list1 = new ArrayList<>();
//        for (OrderCount orderCount : counts) {
//            Long integer = orderCount.getId();
//            list1.add(integer);
//        }
//        if (counts.size() < orderCounts_.size()) {
//            for (OrderCount orderCount : orderCounts_) {
//                Long id1 = orderCount.getId();
//                if (!list1.contains(id1)) {
//                    orderCountMapper.deleteById(id1);
//                }
//            }
//        }
        return Result.success();

    }


    /**
     * 更新取件码对应快递信息状态
     *
     * @param id
     * @return
     */
    @Transactional
    public synchronized Result update3(Integer id) {

        OrderCount orderCount = orderCountMapper.selectById(id);
        if (orderCount == null) {
            return Result.error("id错误");
        }
        if (orderCount.getTakeStatus() == 3) {
            return Result.error("不要重复操作!");
        }

        //更新fake订单的状态
        fakeMapper.updateStateByCountId(id, 3);

        //获取订单状态
        Integer orderId1 = orderCount.getOrderId();
        Orders orders = orderMapper.selectById(orderId1);
        Integer orderStatus = orders.getOrderStatus();

        //1,如果为疑难件,当前不会自动更新真订单的状态
        if (orderStatus == -2) {
            //修改虚拟单状态
            fakeMapper.update(id);
            //修改取件码状态
            orderCountMapper.update(id, 3);
            return Result.success();
        }

        //2.如果不是疑难件,查询是否orderCounts的数量为1
        Integer orderId = orderCount.getOrderId();

        List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(orderId);

        //如果是1，或者查询不到
        if (orderCounts.size() == 1) {
            orderMapper.update(orderId, LocalDateTime.now(), 3);
            Long number = orders.getNumber();
            orderMapper.updateTakeTime(number, LocalDateTime.now());
        }

        orderCountMapper.update(id, 3);
        return Result.success();
    }

    /**
     * 更新取件码对应快递信息状态
     *
     * @param id
     * @return
     */
    @Transactional
    public synchronized Result updatef3(Integer id, String helperRemark) {

        OrderCount orderCount = orderCountMapper.selectById(id);
        if (orderCount == null) {
            return Result.error("id错误");
        }
        if (orderCount.getTakeStatus() == -3) {
            return Result.error("不要重复操作!");
        }

        orderCountMapper.update(id, -3);
        fakeMapper.updateStateByCountId(id, -3);
        orderCountMapper.updateHR(id, helperRemark);
        orderMapper.update(orderCount.getOrderId(), LocalDateTime.now(), -3);
        return Result.success();
    }

    /**
     * 更新取件码对应快递信息状态为待取件
     *
     * @param id
     * @return
     */
    @Transactional
    public synchronized Result update2(Integer id) {

        /**
         * 需要明白，这里的id是count_id
         */

        /* 判断订单是否存在 */
        OrderCount orderCount = orderCountMapper.selectById(id);
        if (orderCount == null) {
            return Result.error("id错误");
        }

        /* 判断当前的取件码状态不能为2(已取件) */
        if (orderCount.getTakeStatus() == 2) {
            return Result.error("不要重复操作!");
        }

        /* 获取订单id */
        Integer orderId = orderCount.getOrderId();

        /* 获取该订单的所有取件码 */
        List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(orderId);

        /**
         * 以下操作实现对订单的自动分类
         */

        /* 取件码不为空*/
        if (orderCounts != null && orderCounts.size() != 0) {

            for (OrderCount orderCount1 : orderCounts) {
                long a = orderCount1.getId().longValue();
                long b = id.longValue();
                if (a == b) {
                    continue;
                }

                /* 发现有非待取件状态 */
                if (orderCount1.getTakeStatus() != 2) {

                    //1.更新取件状态为2
                    orderCountMapper.update(id, 2);

                    //2.此时此刻，肯定存在虚拟单，获取取件码进行分类
                    String takeCode = orderCount.getTakeCode();

                    if (RegularExpression.yd8(takeCode) || RegularExpression.jd(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -21);
                    } else if (RegularExpression.s3d41(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -22);
                    } else if (RegularExpression.s2d38(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -23);
                    } else if (RegularExpression.sf(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -21);
                    } else if (RegularExpression.cabinet(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -24);
                    } else if (RegularExpression.pdd(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -21);
                    } else if (RegularExpression.kf(takeCode)) {
                        fakeMapper.updateStateByCountId(id, -25);
                    }


                    //3.返回结果
                    return Result.success();
                }
            }

            /* 没有其它状态 */
            /*1.单件,可以为整个订单进行分类*/
            if (orderCounts.size() == 1) {

                String takeCode = orderCount.getTakeCode();


                if (RegularExpression.yd8(takeCode) || RegularExpression.jd(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 21);
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.s3d41(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 22);
                    fakeMapper.updateStateByCountId(id, -22);
                } else if (RegularExpression.s2d38(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 23);
                    fakeMapper.updateStateByCountId(id, -23);
                } else if (RegularExpression.sf(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 21);
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.cabinet(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 24);
                    fakeMapper.updateStateByCountId(id, -24);
                } else if (RegularExpression.pdd(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 21);
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.kf(takeCode)) {
                    orderMapper.update(orderId, LocalDateTime.now(), 25);
                    fakeMapper.updateStateByCountId(id, -25);
                }

                //修改取件码状态为2
                orderCountMapper.update(id, 2);
                return Result.success();

            } else {

                /*2.多件，直接将状态改为疑难件*/

                //修改取件码状态为2
                orderCountMapper.update(id, 2);

                //根据取件码类别给虚拟单设置不同的状态
                String takeCode = orderCount.getTakeCode();

                if (RegularExpression.yd8(takeCode) || RegularExpression.jd(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.s3d41(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -22);
                } else if (RegularExpression.s2d38(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -23);
                } else if (RegularExpression.sf(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.cabinet(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -24);
                } else if (RegularExpression.pdd(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -21);
                } else if (RegularExpression.kf(takeCode)) {
                    fakeMapper.updateStateByCountId(id, -25);
                }

                //更新整个订单状态为-2（疑难件）
                orderMapper.update(orderId, LocalDateTime.now(), -2);
                return Result.success();
            }
        } else {
            return Result.error("取件码为空！");
        }

        //如果数据出错，则直接更新，不更改订单状态
//        orderCountMapper.update(id, 2);
    }
}